﻿using FriendFunny.Auth.Jwt.Option;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FriendFunny.Auth.Jwt.Extensions
{
    /// <summary>
    /// JWT扩展方法
    /// </summary>
    public static class JwtExtensions
    {
        /// <summary>
        /// 注册Jwt服务
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection RegisterJwtService(this IServiceCollection services)
        {

            // TODO:这里应该不用读Json 可以直接读取IConfiguration APS.NET会自动将环境变量配置注入IConfiguration
            var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

            var builder = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile(string.IsNullOrWhiteSpace(env) ? "appsettings.json" : $"appsettings.{env}.json", true, reloadOnChange: true);

            var config = builder.Build();

            var jwtSettings = new JwtOptions();
            config.GetSection("JWTSettings").Bind(jwtSettings);

            if(jwtSettings != null) 
            {
                services.AddAuthentication(options =>
                {
                    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidateIssuer = jwtSettings.ValidateIssuer ?? true, //是否验证Issuer
                        ValidIssuer = jwtSettings.ValidIssuer, //发行人Issuer
                        ValidateAudience = jwtSettings.ValidateAudience ?? true, //是否验证Audience
                        ValidAudience = jwtSettings.ValidAudience, //订阅人Audience
                        ValidateIssuerSigningKey = jwtSettings.ValidateIssuerSigningKey ?? true, //是否验证SecurityKey
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.IssuerSigningKey)), //SecurityKey
                        ValidateLifetime = jwtSettings.ValidateLifetime ?? true, //是否验证失效时间
                        ClockSkew = TimeSpan.FromSeconds(jwtSettings.ClockSkew ?? 30), //过期时间容错值，解决服务器端时间不同步问题（秒）
                        RequireExpirationTime = true,
                    };
                });
            }

            return services;
        }
    }
}
